<template>
  <div :class="divClass">
    <img :id="imgId" :src="imgSrc"/>
  </div>
</template>

<script>
  import plupload from 'plupload'
  import {ajax,imgAccessId} from "../data/service";

  export default {
    name: "lazyImgUpload",
    data(){
      return {
        imgSrc:'',
        new_multipart_params : {
          key: '',
          policy: '',
          OSSAccessKeyId: '',
          success_action_status: '200', //让服务端返回200,不然，默认会返回204
          signature: ''
        },
        expire:0,
        host:'',
        dir:'',
        divClass:'',
        imAfterClass:'',
        imResizeWidth:1000,
        imQuality:90,
        imgId:'selectfiles'+this.random_string(6)
      }
    },
    mixins:[ajax],
    mounted(){
      this.imgSrc=this.backgroundImg;
      this.divClass=this.beforeClass;
      this.imAfterClass=this.afterClass;
      this.imResizeWidth = parseInt(this.resizeWidth);  //newVal即是chartData
      this.imQuality = parseInt(this.quality);
      this.initPlUploader();
    },
    methods:{
      initPlUploader() {
        var that=this;
        var plUploader = new plupload.Uploader({
          runtimes : 'html5,flash,silverlight,html4',
          url: 'https://oss.aliyuncs.com',
          browse_button : that.imgId,
          multi_selection:false,
          flash_swf_url : '/static/plupload/Moxie.swf',
          silverlight_xap_url : '/static/plupload/Moxie.xap',
          filters: {
            max_file_size: that.maxSize || '10mb',
            prevent_duplicates: true
          },
          init: {
            FilesAdded: function(up, files) {
              that.openLoading();
              //如果图片过大，需要调用一下压缩
              that.set_upload_param(up, files[0].name);
            },
            FileUploaded: function (up,file,info) {
              that.closeLoading();
              if(info.status==200){
                that.imgSrc=that.host+that.new_multipart_params.key;
                if (that.imAfterClass != '' && that.imAfterClass !== undefined) {
                  that.divClass=that.imAfterClass;
                }
                that.$emit("onSuccess",that.imgSrc);
              }else{
                that.error(info.status+"  "+info.response);
              }
            },
            Error:function(up,err){
              that.error(err.message);
              that.closeLoading();
            }
          }
        });
        plUploader.init();
      },
      set_upload_param(up, filename) {
        var nowDate=new Date();
        var newfilename="xcx/"+nowDate.getFullYear()+""+nowDate.getMonth()+"/"+(this.fileName || this.random_string(32))+this.get_suffix(filename);
        //如果超时了，重新拿key
        var now = Date.parse(new Date()) / 1000;
        if (this.expire < now + 30) {//过期了
          this.doajax(imgAccessId,{},(resp)=>{
            this.host=resp.host;
            this.new_multipart_params.policy=resp.policy;
            this.new_multipart_params.OSSAccessKeyId=resp.accessid;
            this.new_multipart_params.signature=resp.signature;
            this.expire=resp.expire;
            this.dir=resp.dir;
            this.new_multipart_params.key=resp.dir+newfilename;
            this.startUpload(up);
          });
        }else{
          this.new_multipart_params.key=this.dir+newfilename;
          this.startUpload(up);
        }
      },
      startUpload(up){
        up.setOption({
          url: this.host,
          multipart_params: this.new_multipart_params,
          resize: {
            width: this.imResizeWidth,
            quality:this.imQuality,
            crop: false,
            preserve_headers: true
          }
        });
        up.start();
      },
      get_suffix(filename) {
        var pos = filename.lastIndexOf('.');
        var suffix = '';
        if (pos != -1) {
          suffix = filename.substring(pos)
        }
        return suffix;
      },
      random_string(len) {//随机文件名
        len = len || 32;
        var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
        var maxPos = chars.length;
        var pwd = '';
        for (var i = 0; i < len; i++) {
          pwd += chars.charAt(Math.floor(Math.random() * maxPos));
        }
        return pwd;
      }
    },
    props:['backgroundImg','beforeClass','afterClass','resizeWidth','quality', 'maxSize', 'fileName'],
    watch: {
      backgroundImg: function(newVal,oldVal){
        this.imgSrc = newVal;  //newVal即是chartData
      },
      beforeClass:function (newVal,oldVal) {
        this.divClass=newVal;
      },
      resizeWidth: function(newVal,oldVal){
        this.imResizeWidth = parseInt(newVal);  //newVal即是chartData
      },
      quality: function(newVal,oldVal){
        this.imQuality = parseInt(newVal);  //newVal即是chartData
      }
    }
  }
</script>
